<?php

namespace app\admin\controller;

use app\admin\model\Videotask;
use app\common\controller\AliVod;
use app\common\controller\Backend;
use app\admin\model\AivideoNumsLog;
use app\common\model\Attachment;
use think\Cache;
use think\Controller;
use think\Db;
use think\Log;
use think\Request;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Vod\V20180717\VodClient;
use TencentCloud\Vod\V20180717\Models\ComposeMediaRequest;
use TencentCloud\Vod\V20180717\Models\DeleteMediaRequest;
use think\Session;
use app\admin\model\AivideoCompositeLog;
/**
 * 腾讯视频合成管理
 *
 * @icon fa fa-circle-o
 */
class Aivideo extends Backend
{

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Aivideo();

        $auth_level=model('AuthGroupAccess')->where('uid', $this->auth->id)->find();
        if($auth_level->group_id==get_addon_config('douyin')['store_id'])
        {
            $shop_id = Session::get("admin")['shop_id'];
            if(!$shop_id)  $this->error("请绑定商户");
        }

    }


    /**
     * 查看
     */
    public function index()
    {
        $cdk = Cache::get('cdk');
        if ($cdk) {
            $times = $cdk['server']['composetimes'] - $cdk['server']['usedtimes'];
            $mobile = $cdk['server']['mobile'];
        }

        $adminData=model('Admin')->where('id',$this->auth->id)->find();
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();


            if ($this->auth->id != get_addon_config('douyin')['super_id']) {
                $child = model('Admin')->getAgentChild($this->auth->id, 'shop_id');
                if ($child) {
                    $activity_ids=\app\admin\model\Activity::where( 'manystore_id', 'in', $child)->column('id');
                } else {
                    $shop_id = Session::get("admin")['shop_id'];
                    $activity_ids = \app\admin\model\Activity::where('manystore_id', $shop_id)->column('id');
                }

                if (empty(Session::get("admin")['shop_id'])) {
                    $this->model->where($this->model->getTable() . '.admin_id', '=', $this->auth->id);
                } else {
                    $this->model->where($this->model->getTable() . '.activity_id', 'in', $activity_ids);
                }

            }

            $list = $this->model
                ->with(['activity'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('activity')->visible(['title']);
            }


            $data = $list->items();
            foreach ($data as $v) {
                $v->local = str_ireplace(ROOT_PATH . 'public', '', $v->local);
            }
            $result = array("total" => $list->total(), "rows" => $data);

            return json($result);
        }

        //如果是初始管理员，则视频合成额度剩余去中心服务器取值
        $agentQuota = 0;
        if ($this->auth->id === 1) {
            $res = json_decode(file_get_contents('http://zk.ydk1.cn/index.php/api/token/get_video_quota'), true);
            if ($res['code'] == 0) {
                $this->error($res['msg']);
            } else {
                $agentQuota = $res['data']['video_quota'];
            }
        }

        $this->view->assign("times", isset($times) ? $times : $adminData->last_aivideo_nums);
        $this->view->assign("mobile", isset($mobile) ? $mobile : "188888888888");
        $this->view->assign("leftTimes", $this->auth->id === 1 ? $agentQuota : $adminData->last_aivideo_nums);
        $this->view->assign("textletter", $this->auth->id === 1 ? '接口视频剩余额度' : '视频剩余额度');

        return $this->view->fetch();
    }

    private function data2fileId($data)
    {
        if (is_array($data)) {
            foreach ($data as $k => $v) {
                $data[$k] = $this->url2fileId($v);
            }
        } else if (is_string($data)) {
            $data = $this->url2fileId($data);
        }
        return $data;
    }

    private function url2fileId($url)
    {
        $path = parse_url($url, PHP_URL_PATH);
        if (filesize(str_ireplace('\\', '/', ROOT_PATH) . 'public' . $path) / 1024 / 1024 > 10) $this->error('单个文件大小不能超过10M');

        parse_str(parse_url($url, PHP_URL_QUERY), $queryData);
        if (!empty($queryData['vod_id'])) {
            $info = Attachment::get(['id' => $queryData['vod_id'], 'admin_id' => $this->auth->id]);
            if ($info) return $info['file_id'];
        }
        return $url;
    }

    public function submitai()
    {
        $authRes = json_decode(file_get_contents('http://zk.ydk1.cn/index.php/api/token/auth'), true);
        $authInfo = $authRes['data'];
        if (empty($authInfo['authDouYinId'])) $this->error('授权信息错误:authDouYinId');

        $post = $this->request->post();
        $post['name'] = mb_substr($post['name'], 0, 50);

        if ($post['video_list_four']) {
            $video_list_four=$this->data2fileId(explode(',', $post['video_list_four']));
        }else{
            $video_list_four='';
        }


        if ($post['video_list_five']) {
            $video_list_five=$this->data2fileId(explode(',', $post['video_list_five']));
        }else{
            $video_list_five='';
        }



        $video_list_one=$this->data2fileId(explode(',', $post['video_list_one']));
        $video_list_two=$this->data2fileId(explode(',', $post['video_list_two']));
        $video_list_three=$this->data2fileId(explode(',', $post['video_list_three']));
        $video_list[0]=$video_list_one[array_rand($video_list_one)];
        $video_list[1]=$video_list_two[array_rand($video_list_two)];
        $video_list[2]=$video_list_three[array_rand($video_list_three)];

        $video_tmp = [];
        $video_tmp[0] = $video_list_one;
        $video_tmp[1] = $video_list_two;
        $video_tmp[2] = $video_list_three;

        //file_put_contents('log.text', var_export($video_tmp, 1), FILE_APPEND);

        /*if ($video_list_four&&empty($video_list_five)) {
            $video_list[3]=$video_list_four[array_rand($video_list_four)];
        }elseif (empty($video_list_four)&&$video_list_five) {
            $video_list[3]=$video_list_five[array_rand($video_list_five)];
        }elseif ($video_list_four&&$video_list_five) {
            $video_list[3]=$video_list_four[array_rand($video_list_four)];
            $video_list[4]=$video_list_five[array_rand($video_list_five)];
        }*/
        if ($video_list_four&&empty($video_list_five)) {
            $video_list[3]=$video_list_four[array_rand($video_list_four)];
            $video_tmp[3] = $video_list_four;
        }elseif (empty($video_list_four)&&$video_list_five) {
            $video_list[3]=$video_list_five[array_rand($video_list_five)];
            $video_tmp[3] = $video_list_five;
        }elseif ($video_list_four&&$video_list_five) {
            $video_list[3]=$video_list_four[array_rand($video_list_four)];
            $video_list[4]=$video_list_five[array_rand($video_list_five)];
            $video_tmp[3] = $video_list_four;
            $video_tmp[4] = $video_list_five;
        }


        



        $audio_list = $this->data2fileId(explode(',', $post['audio_list']));
        $back_music = $this->data2fileId($post['back_list']);
        $singleVideo_nums = min($post['singleVideo_nums'], count($video_list)); //单个视频使用视频素材数
        $singleAudio_nums = min($post['singleAudio_nums'], count($audio_list));//使用音频素材数
        $video_nums = $post['video_nums'];//预生成视频数
        $Aivideo_nums = $post['Aivideo_nums'];//AI视频低于再预生成
        $adminData=model('Admin')->where('id',$this->auth->id)->find();

        if ($post['video_nums']>50) {
            $this->error('预生成视频数不得大于50');
        }

        if ($this->auth->id !== 1 && $adminData->last_aivideo_nums<$video_nums) {
            $this->error('视频额度不足');
        }
        $videotask_data = compact('singleVideo_nums', 'singleAudio_nums', 'video_nums', 'Aivideo_nums');
        $videotask_data['video_list'] = json_encode($video_tmp,JSON_UNESCAPED_SLASHES);
        $videotask_data['audio_list'] = implode(',', $audio_list);
        $videotask_data['activity_id'] = $post['activity_id'];
        $videotask_data['back_music'] = $back_music;
        $videotask_data['name'] = $post['name'];
        $videotask_data['admin_id'] = $this->auth->id;
        $videotask_data['Aivideo_nums_max'] = $post['Aivideo_nums_max'];
        $M_videotask = new Videotask();
        $M_aivideo = new \app\admin\model\Aivideo();
        $M_videotask->save($videotask_data);
        if (!$taskid = $M_videotask->id) $this->error("添加AI任务不成功,请重试");

        $msg = json_decode(file_get_contents('http://zk.ydk1.cn/index.php/api/token/video_quota?video_amount=' . $video_nums . '&video_name=' . $post['name']), true);

        if ($msg['code'] == 0) $this->error($msg['msg']);


        $aivideo_data = [];
        $tasks = [];
        $taskIdData = [];
        for ($nums = 0; $nums < $video_nums; $nums++) {






            //视频内容不重复
            $video_list[0]=$video_list_one[array_rand($video_list_one)];
            $video_list[1]=$video_list_two[array_rand($video_list_two)];
            $video_list[2]=$video_list_three[array_rand($video_list_three)];



            if ($video_list_four&&empty($video_list_five)) {
                $video_list[3]=$video_list_four[array_rand($video_list_four)];
            }elseif (empty($video_list_four)&&$video_list_five) {
                $video_list[3]=$video_list_five[array_rand($video_list_five)];
            }elseif ($video_list_four&&$video_list_five) {
                $video_list[3]=$video_list_four[array_rand($video_list_four)];
                $video_list[4]=$video_list_five[array_rand($video_list_five)];
            }



            // shuffle($video_list);
            shuffle($audio_list);
            $video_tmp = (array_slice(($video_list), 0, $singleVideo_nums));
            $audio_tmp = (array_slice(($audio_list), 0, $singleAudio_nums));
            $video_name = $post['name'];
            if (config('compose_vendor') === 'ali') {
                $vod_return = (new AliVod)->compose($video_tmp, $audio_tmp, $back_music, $video_name);
                if (!empty($vod_return['task_id'])) $taskIdData[] = $vod_return['task_id'];
            } else {
                $vod_return = $this->general($video_tmp, $audio_tmp, $back_music, $video_name);
            }

            $aitemp = [
                'title' => $video_name,
                'status' => $vod_return['status'],
                'task_id' => $vod_return['task_id'],
                'exception' => $vod_return['exception'],
                'videotask_id' => $taskid,
                'admin_id' => $this->auth->id,
                'activity_id' => $post['activity_id']
            ];
            //经过服务器中转

            $tasks[] = $vod_return['task_id'];
            $aivideo_data[] = $aitemp;
        }


        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'http://zk.ydk1.cn/index.php/api/token/uptask',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => array('taskid' => json_encode($tasks)),
        ));

        curl_exec($curl);

        curl_close($curl);

        if ($taskIdData) {
            $res = AliVod::curl('http://zk.ydk1.cn/index.php/api/auth/mediaToAuthDouyin', ['taskIdData' => $taskIdData, 'authDouYinId' => $authInfo['authDouYinId']]);
            $resData = json_decode($res, 1);
            if (!isset($resData['code']) || $resData['code'] !== 1) {
                if (empty($resData['msg'])) {
                    $this->error('服务器保存数据失败');
                } else {
                    $this->error($resData['msg']);
                }
            }
        }

        model('Admin')->where('id',$this->auth->id)->setInc('aivideo_nums',$video_nums);
        model('Admin')->where('id',$this->auth->id)->setDec('last_aivideo_nums',$video_nums);//扣除可用视频额度


            //视频额度明细
            AivideoNumsLog::create([
                'admin_id'     => $this->auth->id,
                'type'   => 2,
                'aivideo_nums'       => $video_nums,
                'note'  => '合成视频扣除视频额度',
                'create_at'  => date('Y-m-d H:i:s', time()),
            ]);




            //视频合成记录
            AivideoCompositeLog::create([
                'videotask_id'     => $taskid,
                'admin_id'   => $this->auth->id,
                'activity_id'       => $post['activity_id'],
                'video_nums'  => $video_nums,
                'name'  => $post['name'],
                'note'=>'手动合成'
            ]);




        $return = $M_aivideo->saveAll($aivideo_data);

        if ($return) $this->success("添加AI处理视频成功");
    }


    public function general($videos, $audios, $back_music, $name)
    {
        if (!$config = Cache::get('cdk')) {
            $data_auth = json_decode(file_get_contents('http://zk.ydk1.cn/index.php/api/token/auth'), true);
            if ($data_auth['code'] == 0) {
                $this->error($data_auth['msg']);
            }

            $config = $data_auth['data'];
            Cache::set('cdk', $config, 86400);
        }


        try {
            $cred = new Credential($config['SecretId'], $config['SecretKey']);
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("vod.tencentcloudapi.com");
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new VodClient($cred, "", $clientProfile);
            $req = new ComposeMediaRequest();
            $video_template = [
                "VideoItem" => array(
                    "AudioOperations" => array(
                        array(
                            "VolumeParam" => array(
                                /* 1：视频音频静音 2：原声 */
                                "Mute" => 1
                            ),
                            /*Volume 需要操作音量 不操作音量为空*/
                            "Type" => "Volume"
                        )
                    ),
                    /*媒资库视频ID或媒资库url 不能使用对象存储url与第三方URL 需要该视频转码 目前使用转码是STD-H264-MP4-720P*/
                    "SourceMedia" => ""
                ),
                /*本素材类型：Video 视频 Audio ：音频轨道 Sticker ：贴图轨道*/
                "Type" => "Video"
            ];

            $audio_template = [
                "AudioItem" => array(
                    "AudioOperations" => array(
                        array(
                            "VolumeParam" => array(
                                "Gain" => 5
                            ),
                            "Type" => "Volume"
                        )
                    ),
                    "SourceMedia" => ""
                ),
                "Type" => "Audio"
            ];

            $params = array(
                "Tracks" => array(
                    /*视频轨道开始*/
                    array(
                        "TrackItems" => [],
                        "Type" => "Video"
                    ),
                    /*语音合成轨道开始*/
                    array(
                        "TrackItems" => [],
                        /*语音轨道定义该轨道为音频*/
                        "Type" => "Audio"
                    ),
                    /*背景音乐合成轨道开始*/
                    array(
                        "TrackItems" => array(
                            array(
                                "AudioItem" => array(
                                    "SourceMedia" => $back_music,
                                    /*截取时长为86秒  三个视频素材总时长=86秒*/
                                ),
                                "Type" => "Audio"
                            )
                        ),
                        "Type" => "Audio"
                    )
                ),
                "Output" => array(
                    /*输出文件名称与格式*/
                    "FileName" => $name,
                    "Container" => "mp4"
                ),


            );

            $videoItems = [];
            foreach ($videos as $video) {
                $video_template['VideoItem']['SourceMedia'] = $video;
                $videoItems[] = $video_template;
            }
            $audioItems = [];
            foreach ($audios as $audio) {
                $audio_template['AudioItem']['SourceMedia'] = $audio;
                $audioItems[] = $audio_template;
            }
            $params['Tracks'][0]['TrackItems'] = $videoItems;
            $params['Tracks'][1]['TrackItems'] = $audioItems;

            $req->fromJsonString(json_encode($params));
            $resp = $client->ComposeMedia($req);

            return ['status' => 1, 'task_id' => $resp->TaskId, 'exception' => ''];
        } catch (TencentCloudSDKException $e) {

            return ['status' => 0, 'task_id' => '', 'exception' => $e];
        }


    }





    /**
     * 查看
     */
    public function index2()
    {


        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();


            if ($this->auth->id != get_addon_config('douyin')['super_id']) {
                $child = model('Admin')->getAgentChild($this->auth->id, 'shop_id');
                if ($child) {
                    $activity_ids=\app\admin\model\Activity::where( 'manystore_id', 'in', $child)->column('id');
                } else {
                    $shop_id = Session::get("admin")['shop_id'];
                    $activity_ids = \app\admin\model\Activity::where('manystore_id', $shop_id)->column('id');
                }

                        $this->model->where($this->model->getTable() . '.activity_id', 'in', $activity_ids);

            }

            //获取自身和自身的所有下级账号ID
            $dbPrefix = config('database.prefix');
            $adminData = Db::table($dbPrefix . 'admin')->field('id,pid')->select();
            $posterityIdData = getPosterityId($adminData, $this->auth->id);
            if (is_array($posterityIdData)) {
                $posterityIdData = array_merge($posterityIdData, [$this->auth->id]);
            } else {
                $posterityIdData = [$this->auth->id];
            }

            $list = AivideoCompositeLog::with(['activity'])->whereIn($dbPrefix . 'video_composite_log.admin_id', $posterityIdData)


                ->paginate($limit);




            foreach ($list as $row) {
                $row->getRelation('activity')->visible(['title']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());




            return json($result);
        }


    }

    public function upload()
    {
        $post = $this->request->post();
        $post['title'] = mb_substr($post['title'], 0, 50);
        $videoData = explode(',', $post['video']);

        $data = array();
        foreach ($videoData as $video) {
            $data[] = [
                'title' => $post['title'],
                'status' => 2,
                'videotask_id' => 0,
                'task_id' => '',
                'exception' => '',
                'createtime' => time(),
                'video' => '/' . trim($video, '/'),
                'updatetime' => time(),
                'admin_id' => $this->auth->id,
                'activity_id' => $post['activity_id'],
                'local' => '/' . trim(trim(str_replace('\\', '/', ROOT_PATH), '/') . '/public/' . trim($video, '/'), '/'),
            ];
        }

        $result = $this->model->saveAll($data);
        if ($result) {
            $this->success('上传成功');
        } else {
            $this->error('上传视频失败');
        }
    }

    public function del($ids = '')
    {
        if (!$config = Cache::get('cdk')) {
            $data_auth = json_decode(file_get_contents('http://zk.ydk1.cn/index.php/api/token/auth'), true);
            if ($data_auth['code'] == 0) {
                $this->error($data_auth['msg']);
            }

            $config = $data_auth['data'];
            Cache::set('cdk', $config, 86400);
        }

        $info = $this->model::find($ids);
        if (!$info) $this->error('未找到视频信息');
        if (config('compose_vendor') !== 'ali' && !empty($info->file_id)) {
            try {
                $cred = new Credential($config['SecretId'], $config['SecretKey']);
                $httpProfile = new HttpProfile();
                $httpProfile->setEndpoint("vod.tencentcloudapi.com");

                $clientProfile = new ClientProfile();
                $clientProfile->setHttpProfile($httpProfile);
                $client = new VodClient($cred, "", $clientProfile);
                $req = new DeleteMediaRequest();

                $params = array(
                    "FileId" => $info->file_id
                );
                $req->fromJsonString(json_encode($params));
                $resp = $client->DeleteMedia($req);
                $resData = json_decode($json = $resp->toJsonString(), true);
                if (!isset($resData['RequestId'])) $this->error($json);
            } catch (TencentCloudSDKException $e) {
                $this->error($e->getMessage());
            }
        }
        parent::del($ids);
    }

}
